import { useEffect, useRef, useCallback } from 'react';
// import { videoApi } from '../api'; // Commented out - video functionality removed
import type { Video } from '../api/types';

interface UseVideoPollingProps {
  videos: Video[];
  setVideos: React.Dispatch<React.SetStateAction<Video[]>>;
  pollingInterval?: number; // 轮询间隔（毫秒）
  maxRetries?: number; // 最大重试次数
}

interface VideoPollingState {
  retryCount: Record<string, number>;
  pollingTimers: Record<string, number>;
}

/**
 * 视频状态自动轮询 Hook
 * 自动轮询 pending 和 processing 状态的视频，直到完成或失败
 * 注意: 视频功能已移除，此 Hook 仅作为占位符保留
 */
export const useVideoPolling = ({
  videos,
  setVideos,
  pollingInterval = 5000, // 默认5秒
  maxRetries = 20, // 默认最多重试20次（约100秒）
}: UseVideoPollingProps) => {
  // 视频功能已移除，参数暂时未使用但保留接口兼容性
  void setVideos;
  void maxRetries;
  const stateRef = useRef<VideoPollingState>({
    retryCount: {},
    pollingTimers: {},
  });

  const updateVideoStatus = useCallback(async (videoId: string) => {
    try {
      // Video API removed - placeholder function that does nothing
      console.log(`Video polling for ${videoId} - feature disabled`);
      return false;
      /*
      const newStatus = await videoApi.getStatus(videoId);

      setVideos(prevVideos => 
        prevVideos.map(video => {
          const currentVideoId = video.video_id || video.id;
          if (currentVideoId === videoId) {
            return {
              ...video,
              status: newStatus?.status || video.status,
              video_url: newStatus?.video_url || video.video_url,
              thumbnail_url: newStatus?.thumbnail_url || video.thumbnail_url,
              gif_url: newStatus?.gif_url || video.gif_url,
              duration: newStatus?.duration || video.duration,
              error: newStatus?.error || video.error
            };
          }
          return video;
        })
      );

      // 如果状态已完成或失败，停止轮询
      if (newStatus?.status && ['completed', 'failed'].includes(newStatus.status.toLowerCase())) {
        stopPollingVideo(videoId);
        return true; // 表示轮询应该停止
      }

      return false; // 表示需要继续轮询
    } catch (error) {
      console.error(`Failed to update status for video ${videoId}:`, error);
      
      // 增加重试计数
      const currentRetries = stateRef.current.retryCount[videoId] || 0;
      stateRef.current.retryCount[videoId] = currentRetries + 1;

      // 如果重试次数过多，停止轮询
      if (currentRetries >= maxRetries) {
        console.warn(`Max retries reached for video ${videoId}, stopping polling`);
        stopPollingVideo(videoId);
        return true;
      }

      return false;
      */
    } catch (error) {
      console.error(`Video polling error for ${videoId}:`, error);
      return false;
    }
  }, []);

  const stopPollingVideo = useCallback((videoId: string) => {
    const timer = stateRef.current.pollingTimers[videoId];
    if (timer) {
      console.log(`Stopping polling for video: ${videoId}`);
      clearInterval(timer);
      delete stateRef.current.pollingTimers[videoId];
      delete stateRef.current.retryCount[videoId];
    }
  }, []);

  const startPollingVideo = useCallback(
    (videoId: string) => {
      // 如果已经在轮询，先停止
      stopPollingVideo(videoId);

      console.log(`Starting polling for video: ${videoId}`);

      // 重置重试计数
      stateRef.current.retryCount[videoId] = 0;

      // 立即执行一次状态更新
      updateVideoStatus(videoId);

      // 设置定时器
      const timer = setInterval(async () => {
        const shouldStop = await updateVideoStatus(videoId);
        if (shouldStop) {
          clearInterval(timer);
          delete stateRef.current.pollingTimers[videoId];
          delete stateRef.current.retryCount[videoId];
        }
      }, pollingInterval);

      stateRef.current.pollingTimers[videoId] = timer;
    },
    [updateVideoStatus, pollingInterval, stopPollingVideo]
  );

  const startPollingAll = useCallback(() => {
    videos.forEach(video => {
      const videoId = video.video_id || video.id;
      const status = video.status?.toLowerCase();

      // 只为 pending 或 processing 状态的视频启动轮询
      if (videoId && status && ['pending', 'processing'].includes(status)) {
        startPollingVideo(String(videoId));
      }
    });
  }, [videos, startPollingVideo]);

  const stopPollingAll = useCallback(() => {
    Object.keys(stateRef.current.pollingTimers).forEach(videoId => {
      stopPollingVideo(videoId);
    });
  }, [stopPollingVideo]);

  // 当视频列表变化时，自动启动轮询
  useEffect(() => {
    startPollingAll();

    // 清理函数：组件卸载时停止所有轮询
    return () => {
      stopPollingAll();
    };
    // 只在视频ID列表变化时重新运行
  }, [videos, startPollingAll, stopPollingAll]);

  // 提供手动控制函数
  return {
    startPollingVideo,
    stopPollingVideo,
    startPollingAll,
    stopPollingAll,
    updateVideoStatus,
    isPolling: (videoId: string) => !!stateRef.current.pollingTimers[videoId],
    getRetryCount: (videoId: string) => stateRef.current.retryCount[videoId] || 0,
  };
};

export default useVideoPolling;
